package com.csu.servlet;

import com.csu.entiry.BorrowInfo;
import com.csu.service.BorrowInfoService;
import com.csu.service.impl.BorrowInfoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PipedReader;
import java.sql.Date;
import java.text.SimpleDateFormat;

@WebServlet(name = "UpdateBorrowInfoServlet", urlPatterns = "/UpdateBorrowInfoServlet")
public class UpdateBorrowInfoServlet extends HttpServlet {
    private BorrowInfoService borrowInfoService = new BorrowInfoServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookName = req.getParameter("bookName");
        String  reader = req.getParameter("reader");
        String str = req.getParameter("borrowDate");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date d = null;
        try {
            d = format.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date date1 = new java.sql.Date(d.getTime());

        str = req.getParameter("returnDate");
        try {
            d = format.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date date2 = new java.sql.Date(d.getTime());

        String SisReturn = req.getParameter("isReturn");
        int isReturn = (SisReturn != null) ? 1 : 0;

        BorrowInfo borrowInfo = new BorrowInfo();
        borrowInfo.setBookName(bookName);
        borrowInfo.setReader(reader);
        borrowInfo.setBorrowDate(date1);
        borrowInfo.setReturnDate(date2);
        borrowInfo.setIsReturn(isReturn);
        borrowInfo.setBorrowId(Integer.parseInt(req.getParameter("borrowId")));

        boolean result =  borrowInfoService.updateInfo(borrowInfo);
        if(result){
            req.getSession().setAttribute("msg", "更新成功！");
        }else{
            req.getSession().setAttribute("msg", "更新失败！");
        }
        resp.sendRedirect(req.getContextPath() + "/GetBorrowInfoServlet");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
